<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>聊天室</title>
	<script src="socket.io.min.js"></script>
</head>
<body>
	<div id="login">
		<input type="text" placeholder="请输入聊天室的昵称，按回车登陆！">
	</div>
	<div id="room">
		<p>欢迎的<span id="userNameSpan" style="color:red;">zhangsan</span>
			到来！当前聊天室在线人数为<span id="numSpan" style="color:green;">0</span>!</p>
		<hr/>
		<input id="context" type="text"> <button>发送</button>
		<hr/>
		<textarea id="roomContext" rows="100" cols="100"></textarea>
	</div>
</body>
<script>
	const loginDiv = document.querySelector("#login");
	const roomDiv = document.querySelector("#room");
	const userNameSpan = roomDiv.querySelector("#userNameSpan");
	const onLineNumSpan = roomDiv.querySelector("#numSpan");
	const roomContext = roomDiv.querySelector("#roomContext");
	const contextInp = roomDiv.querySelector("#context");
	roomDiv.style.display = "none";
	loginDiv.querySelector("input").onkeyup = async function(e){
		if(e.keyCode === 13){
			const userName = e.target.value.trim();
			if(userName.length<4){
				alert("昵称的长度不允许小于4");
				return;
			}
			const {ok} = await fetch("/login",{
				method:"post",
				headers:{
					"Content-Type":"application/json"
				},
				body:JSON.stringify({
					userName
				})
			}).then(value=>value.json());
			if(ok === 1){
				const ws = io.connect("/");
				ws.emit("intoRoom",userName);
				roomDiv.style.display = "block";
				loginDiv.style.display = "none";
				userNameSpan.innerText = userName;
				// rootUserName:聊天室操作的用户名
				// num:在线人数
				// isIn:true 进入聊天室 false 离开聊天室
				ws.on("upRoom",function(roomUserName,num,isIn){
					// 更新在线人数
					onLineNumSpan.innerText = num;
					roomContext.value += "\n"+roomUserName+(isIn?'进入':'离开')+"了直接间"
					
				})
				ws.on("roomSay",function(rootUserName,context){
					roomContext.value+="\n"+rootUserName+":"+context;
				})
				roomDiv.querySelector("button").onclick =function(){
					const context = contextInp.value.trim();
					if(context.length<1){
						alert("输入内容不允许小于1");return;
					}else{
						ws.emit("say",userName,context);
					}
				}
				
				
			}else{
				alert("聊天室中已经存在该用户");
			}
		}
	}
</script>
</html>